import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { useMount } from 'ahooks'
import PropTypes from 'prop-types'
import zhCN from 'antd/locale/zh_CN'
import { ConfigProvider, App } from 'antd'
import { lazy, Suspense, useState } from 'react'
import { BrowserRouter, useRoutes } from 'react-router-dom'

import Localhost from '../Log/LoginBox/localhost'
import { IndexedDBFun } from '../Utils/IndexedDB'
import { judgeBrowserVersion } from '../Utils/Judgment'

dayjs.locale('zh-cn')

const { hostname } = window.location

const Log = lazy(() => import('../Log'))
const Loading = lazy(() => import('../Views/LoadSvg'))
const VersionTips = lazy(() => import('../Views/VersionTips'))
const Admin = lazy(() => import('../Admin'))
const Common = lazy(() => import('../Common'))
const Start = lazy(() => import(`../Start`))
const Page = lazy(() => import(`../Start/Page.jsx`))
const Home = lazy(() => import(`../Start/Home.jsx`))

const CommonRouter = [
    { path: '/', element: <Log /> },
    { path: 'Common', element: <Common /> }
]

const ProjectRouter = [
    { path: '/', element: <Log /> },
    { path: 'Admin', element: <Admin /> },
    {
        path: 'Start',
        element: <Start />,
        children: [
            { path: 'Home', element: <Home /> },
            { path: 'Page/:page', element: <Page /> },
        ]
    }
]

const Main = () => {
    const [Router, setRouter] = useState()
    const [EdiTionState, setEdiTionState] = useState(true)
    const Routes = ({ data }) => {
        Routes.propTypes = { data: PropTypes.object }
        return useRoutes(data)
    }
    useMount(() => {
        if (hostname !== 'localhost') {
            const BrowserVersion = judgeBrowserVersion()
            setEdiTionState(BrowserVersion)
            if (BrowserVersion) {
                window.webDB = IndexedDBFun()
                if (hostname === 'common-lib.ljkjkf.com') setRouter(CommonRouter)
                else setRouter(ProjectRouter)
            }
        }
    })
    if (hostname === 'localhost') return <Localhost />
    else
        return (
            <ConfigProvider locale={zhCN}>
                <App>
                    {Router ?
                        <BrowserRouter>
                            <Suspense fallback={<Loading />} >
                                {EdiTionState ? <Routes data={Router} /> : <VersionTips />}
                            </Suspense>
                        </BrowserRouter> : <Loading />
                    }
                </App>
            </ConfigProvider>
        )
}

export default Main